import JsbUtil from "../platform/JsbUtil";
import JayUtil from "./JayUtil";



export default class CameraUtil {

    public static mFileSystemManager = null;
    // 拍照的临时照片地址
    public static tempFilePath = null;
    public static camera = null;
    public static texture = null;
    public static head = null;
    public static canvas = null;
    public static ctx = null;
    //是否已保存过
    public static isSave = false;
    public static address = null;
    public static filePath = null;
    public static colorArray = [];
    public static headImgData = null;
    public static headPath = null;
    //需要截屏时 调用此方法
    public static captureAndShow(camera, successFunction?) {
        let spriteFrame;
        Log('当前平台 = ', JayUtil.getPlatform())
        if (JayUtil.getPlatform() == 'weChatGame') {
            //WX
            this.captureWeb(camera);
            const filPath = this.save();
            var spriteName = this.getCurrDate() + 'png';
            this.LocalSaveFile(filPath, spriteName);
            this.address = this.getWxUserFilePath() + spriteName;
        }
        else if (JayUtil.getPlatform() == 'android') {
            //安卓
            Log('这是安卓这是安卓');
            spriteFrame = this.captureJSB();
            Log('这是安卓这是安卓', spriteFrame);

        }
        else {
            // WEB 
            var img = this.captureWeb(camera);
            Log('cc.sys.isNative ---> ' + cc.sys.isNative);
            let texture = new cc.Texture2D();
            texture.initWithElement(img);
            spriteFrame = new cc.SpriteFrame(texture);
        }
        if (successFunction) {
            successFunction(spriteFrame);
        }
        return spriteFrame;
    }
    //需要截屏直接保存的 调用此方法
    public static captureAndSave(camera) {
        let spriteFrame;
        if (JayUtil.getPlatform() == 'weChatGame') {
            //WX
            spriteFrame = this.captureWeb(camera);
            const filPath = this.save();
            this.quickSave();
        }
        else if (JayUtil.getPlatform() == 'android') {
            //保存
            spriteFrame = this.captureJSB(camera);
            this.saveJSP();
            this.saveToAndroid(this.filePath);
        }
        else {
            // WEB 
            var img = this.captureWeb(camera);
            Log('cc.sys.isNative ---> ' + cc.sys.isNative);
            let texture = new cc.Texture2D();
            texture.initWithElement(img);
            spriteFrame = new cc.SpriteFrame(texture);
            // spriteFrame.setTexture(texture);
        }
        return spriteFrame;
    }
    public static captureJSB(camera?) {
        //需要自己自行再创建一个 Camera depth要高于MainCamera 不然会黑屏 
        if (!camera) {
            camera = cc.find('Canvas/Camera').getComponent(cc.Camera);
        }
        this.texture = new cc.RenderTexture();
        this.texture.initWithSize(cc.winSize.width, cc.winSize.height);
        camera.targetTexture = this.texture;
        // 渲染一次摄像机，即更新一次内容到 RenderTexture 中
        camera.render(camera.node.parent);
        this.texture.handleLoadedTexture();
        return new cc.SpriteFrame(this.texture);
    }
    public static captureWeb(camera?) {

        if (JayUtil.getPlatform() == 'weChatGame') {
            window['wx'].showLoading({
                title: '拍照中...'
            })
        }

        let s3 = new Date().getTime();
        this.isSave = false;

        //需要自己自行再创建一个 Camera depth要高于MainCamera 不然会黑屏 
        this.camera = camera;
        this.texture = new cc.RenderTexture();
        this.texture.initWithSize(cc.winSize.width, cc.winSize.height);
        this.camera.targetTexture = this.texture;

        // 渲染一次摄像机，即更新一次内容到 RenderTexture 中
        this.camera.render(this.camera.node.parent);
        // 这样我们就能从 RenderTexture 中获取到数据了
        let data = this.texture.readPixels();
        let width = this.texture.width;
        let height = this.texture.height;

        if (this.canvas == null) {
            this.canvas = document.createElement('canvas');
            this.ctx = this.canvas.getContext('2d');
            this.canvas.width = width;
            this.canvas.height = height;
        }

        let rowBytes = width * 4;
        for (let row = 0; row < height; row++) {
            let srow = height - 1 - row;
            let imageData = this.ctx.createImageData(width, 1);
            let start = srow * width * 4;
            for (let i = 0; i < rowBytes; i++) {
                imageData.data[i] = data[start + i];
            }

            this.ctx.putImageData(imageData, 0, row);
        }

        if (CC_DEBUG) {
            // cc.log(`生成截图耗时:  ${new Date().getTime() - s3} ms`);
        }

        var dataURL = this.canvas.toDataURL("image/png");
        var img = document.createElement("img");
        img.src = dataURL;

        return img;
    }
    public static saveJSP() {
        let data = this.filpYImage(this.texture.readPixels(), this.texture.width, this.texture.height);
        this.filePath = jsb.fileUtils.getWritablePath() + "Phone_" + new Date().getTime() + '.png';
        Log('filePath = ', this.filePath);
        jsb.saveImageData(data, this.texture.width, this.texture.height, this.filePath);
        //JS调用JAVA saveTextureToLocal 方法 参数为 filePath 也就是路径
        return this.filePath;
    }
    public static saveToAndroid(path) {
        Log('保存图片到本地,地址为:', path)
        JsbUtil.savePictureToLocal(path);
        // jsb.reflection.callStaticMethod("org/cocos2dx/javascript/CocosHelp", "saveTextureToLocal", "(Ljava/lang/String;)V", this.filePath);
    }
    public static saveBz() {
        JsbUtil.saveWallpaper(this.filePath);
    }
    public static captureHeadShow(camera) {
        let spr = this.captureHead(camera, 300, 300);
        Log('这波好像没出错啊')
        let headPath = this.saveHeadJsb();
        JsbUtil.savePictureToLocal(headPath);
        return spr;
    }
    public static captureHead(camera, width, height) {
        if (!camera) {
            camera = cc.find('Canvas/Camera').getComponent(cc.Camera);
        }
        this.head = new cc.RenderTexture();
        this.head.initWithSize(cc.winSize.width, cc.winSize.height);
        camera.targetTexture = this.head;
        // 渲染一次摄像机，即更新一次内容到 RenderTexture 中
        camera.render(camera.node.parent);
        this.head.handleLoadedTexture();
        //切割图片,此时这个图片是直接显示给玩家看的,这个速度快
        let startx = cc.winSize.width / 2 - 150;
        let starty = cc.winSize.height / 2 - 150
        // let cj = new cc.SpriteFrame(this.head,cc.rect(startx,starty,300,300))

        //开始日狗!------------------------------------------------------------------------------------------------
        let data = this.head.readPixels();
        this.colorArray = [];
        for (let i = 0; i < data.length; i += 4) //4个值构成RGBA
        {
            let color = { 'r': data[i], 'g': data[i + 1], 'b': data[i + 2], 'a': data[i + 3] };
            this.colorArray.push(color);
        }
        /**
         *   12,13,14,15
         *   8, 9 ,10,11
         *   4, 5, 6 ,7
         *   0, 1, 2 ,3
         */
        let sprWidth = Math.round(cc.winSize.width);
        let imageData = new Uint8Array(width * height * 4);
        let index = 0;
        for (let i = 0; i < this.colorArray.length; i++) {
            let x = i % sprWidth;
            let y = Math.floor(i / sprWidth);
            if (x >= startx && x < startx + width && y >= starty && y < starty + height) {
                imageData[index + 3] = this.colorArray[i]['a'];
                imageData[index + 2] = this.colorArray[i]['b'];
                imageData[index + 1] = this.colorArray[i]['g'];
                imageData[index] = this.colorArray[i]['r'];
                index += 4;
            }
        }
        Log('i=', index)
        let format = this.head.getPixelFormat();
        Log('文理格式 = ', format)
        imageData = this.filpYImage(imageData, 300, 300)
        this.headImgData = imageData;
        this.head = new cc.RenderTexture();
        this.head.initWithData(imageData, format, 300, 300);
        let dj = new cc.SpriteFrame(this.head)
        //----------------------------------------------------------------------------------
        return dj;
    }
    public static saveHeadJsb() {
        this.headPath = jsb.fileUtils.getWritablePath() + "Phone_" + new Date().getTime() + '.png';
        Log('headPath = ', this.headPath, 'data 新= ');
        jsb.saveImageData(this.headImgData, this.head.width, this.head.height, this.headPath);
        Log('jsbSaveSuccess = ');

        //JS调用JAVA saveTextureToLocal 方法 参数为 filePath 也就是路径
        return this.headPath;
    }


    public static save() {
        if (JayUtil.getPlatform() == 'weChatGame' && this.canvas && this.isSave == false) {
            this.isSave = true;
            this.tempFilePath = this.canvas.toTempFilePathSync();
            return this.tempFilePath;
        } else {
            Log('非微信环境/canvas为空/不重复缓存');
            return "";
        }
    }
    public static filpYImage(data, width, height) {
        // create the data array
        let picData = new Uint8Array(width * height * 4);
        let rowBytes = width * 4;
        for (let row = 0; row < height; row++) {
            let srow = height - 1 - row;
            let start = srow * width * 4;
            let reStart = row * width * 4;
            // save the piexls data
            for (let i = 0; i < rowBytes; i++) {
                picData[reStart + i] = data[start + i];
            }
        }
        return picData;
    }
    //---------------------------------------------微信本地文件的方法---------------------------------------------
    public static LocalSaveFile(path, saveFileName) {
        if (JayUtil.getPlatform() != 'weChatGame') {
            Log('不是微信 滚你丫的又想坑老子安卓')
            return;
        }
        var self = this;
        this.mFileSystemManager = window['wx'].getFileSystemManager();

        Log('本地保存的路径=', path)
        this.mFileSystemManager.saveFile({
            tempFilePath: path,
            filePath: self.getWxUserFilePath() + saveFileName,//window['wx'].env.USER_DATA_PATH+'/Levle1.zip',
            success: function (res) {
                Log('保存成功,路径', self.getWxUserFilePath() + saveFileName)
            },
            fail: function (res) {
                Log(saveFileName + '保存失败 + ', res.errMsg);
            }
        })
    }
    public static LocalReadFile() {
        if (JayUtil.getPlatform() != 'weChatGame') {
            Log('不是微信 滚你丫的又想坑老子安卓')
            return;
        }
        var self = this;
        this.mFileSystemManager = window['wx'].getFileSystemManager();
        let fileArray = this.mFileSystemManager.readdirSync(window['wx'].env.USER_DATA_PATH + '/myFile');
        Log('fileArray = ', fileArray);
        return fileArray;
    }
    public static deleteFile(address) {
        if (JayUtil.getPlatform() != 'weChatGame') {
            Log('不是微信 滚你丫的又想坑老子安卓')
            return;
        }
        this.mFileSystemManager = window['wx'].getFileSystemManager();
        this.mFileSystemManager.removeSavedFile({
            filePath: address,
            success: function () {
                Log('删除成功');
            },
            fail: function (res) {
                Log('删除失败 ,', res.errMsg);
            }
        });
    }
    public static getWxUserFilePath() {
        if (JayUtil.getPlatform() != 'weChatGame') {
            Log('大哥啊 真的不是微信')
            return "";
        }
        return window['wx'].env.USER_DATA_PATH + "/" + 'myFile/';
    }
    //*********************************************微信本地文件的方法end******************************************
    //---------------------------------------------微信本地缓存的方法,这套流程暂时不用---------------------------------------------
    //截图后存储本地环节,此方法是存到微信storage中
    public static LocalStorage(data) {
        var album = JayUtil.getLocalStorage('Album');
        if (album == 'default') {
            album = '';
            let count = 0;
        }
        else {
            var AlbumArray = UIHelper.splitStringToNumberArray(album, '|');
            let count = AlbumArray.length - 1;
            if (count >= 20) {
                WxApiHelper.makeText('游戏相册已满,不存储', 0, 1);
                return;
            }
        }

        var dateStr = this.getCurrDate();
        album = album + dateStr;
        JayUtil.setLocalStorage('Album', album);
        JayUtil.setLocalStorage(dateStr, data);
    }
    //从微信storage中将图片还原出来
    public static restoreStorage(callback) {
        var album = JayUtil.getLocalStorage('Album');
        if (album == 'default') {
            album = '';
            return null;
        }
        else {
            let AlbumArray = UIHelper.splitStringToNumberArray(album, '|');
            let count = AlbumArray.length - 1;
            for (let i = 0; i < count; i++) {
                let key = AlbumArray[i] + '|';
                let imgUrl = JayUtil.getLocalStorage(key);
                if (imgUrl.indexOf('image') < 0) {
                    continue;
                }
                let img = new Image();
                img.onload = () => {
                    let texture = new cc.Texture2D();
                    texture.initWithElement(img);
                    texture.handleLoadedTexture();
                    let spriteFrame = new cc.SpriteFrame(texture);
                    callback(spriteFrame, key);
                };
                img.src = imgUrl;
            }
        }
    }
    //将图片从微信storage中删除
    public static removeStorage(key) {
        // window['wx'].removeStorageSync(key);
        JayUtil.rmLocalStorage(key);
        var album = JayUtil.getLocalStorage('Album');
        album.replace(key, '');
        JayUtil.setLocalStorage('Album', album);
    }
    //***********************************************************微信本地缓存方法end***********************************************************
    public static getCurrDate() {
        var myDate = new Date();
        var n = myDate.getFullYear();
        var y = myDate.getMonth();
        var r = myDate.getDate();
        var h = myDate.getHours();
        var m = myDate.getMinutes();
        var s = myDate.getSeconds();
        var str = n + '*' + y + '*' + r + '*' + h + '*' + m + '*' + s;
        return str;
    }
    public static quickShare(title) {
        if (JayUtil.getPlatform() == 'weChatGame') {
            if (this.tempFilePath != null) {
                // const shareTitle = title? title:'看我今天的装扮，怎么样？';
                ShareHelper.startShare(null, 'invite', this.tempFilePath)
                // window['wx'].shareAppMessage({
                //     title: shareTitle,
                //     imageUrl: this.tempFilePath
                // })
            } else {
                Log('临时文件不存在，不分享');
            }
        } else {
            Log('非微信环境，不分享');
        }
    }
    public static quickSave() {
        var self = this;
        if (JayUtil.getPlatform() == 'weChatGame') {
            window['wx'].showLoading({
                title: '正在保存照片...'
            })
            window['wx'].saveImageToPhotosAlbum({
                filePath: this.tempFilePath,
                success(res) {
                    Log('保存成功 path', self.tempFilePath, res);
                    window['wx'].showToast({
                        title: '成功保存到系统相册'
                    })
                },
                fail(res) {
                    Log('保存失败', res);
                    window['wx'].showToast({
                        title: '保存失败'
                    })
                },
                complete() {
                    window['wx'].hideLoading();
                }
            })
        } else {
            Log('非微信环境，无法保存');
        }
    }
}
